package com.qs.javame.thread.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 测试自定义线程池对象
 * 构建一个corePoolSize=2，maximumPoolSize=4，阻塞队列容量为2的线程池，main线程提交7个任务，观察测试结果。
 * 测试结果：main线程在提交第七个task时，出现RejectedExecutionException异常。
 */
public class TestPool {

    public static void main(String[] args) {
        //自定义一个线程池对象
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2,4,
                0, TimeUnit.SECONDS,new ArrayBlockingQueue<>(2));
        Runnable task = new Task();
        threadPool.execute(task);
        threadPool.execute(task);
        threadPool.execute(task);
        threadPool.execute(task);
        threadPool.execute(task);
        threadPool.execute(task);

//        threadPool.execute(task);
        threadPool.shutdown();
    }
}

//线程任务
class Task implements Runnable{

    @Override
    public void run() {
        //模拟线程任务执行时间，睡眠500ms
        try {
            TimeUnit.NANOSECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "-正在执行任务");
    }
}
